#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include "bmp280.h"
#include <unistd.h>

int calculate_pressure( struct bmp280_dat bmp_dat, float *pressure, float *Tempture )
{
    int var1, var2, t_fine, p;
    //Temperature
    var1 = (((double)bmp_dat.adc_T)/16384.0-((double)bmp_dat.dig_T1)/1024.0)*((double)bmp_dat.dig_T2);
    var2 = ((((double)bmp_dat.adc_T)/131072.0-((double)bmp_dat.dig_T1)/8192.0)*(((double)bmp_dat.adc_T)
                /131072.0-((double)bmp_dat.dig_T1)/8192.0))*((double)bmp_dat.dig_T3);

    t_fine = (unsigned int)(var1+var2);

    *Tempture = (var1+var2)/5120.0;

    var1 = ((double)t_fine/2.0)-64000.0;
    var2 = var1*var1*((double)bmp_dat.dig_P6)/32768.0;
    var2 = var2 +var1*((double)bmp_dat.dig_P5)*2.0;
    var2 = (var2/4.0)+(((double)bmp_dat.dig_P4)*65536.0);
    var1 = (((double)bmp_dat.dig_P3)*var1*var1/524288.0+((double)bmp_dat.dig_P2)*var1)/524288.0;
    var1 = (1.0+var1/32768.0)*((double)bmp_dat.dig_P1);
    p = 1048576.0-(double)bmp_dat.adc_P;
    p = (p-(var2/4096.0))*6250.0/var1;
    var1 = ((double)bmp_dat.dig_P9)*p*p/2147483648.0;
    var2 = p*((double)bmp_dat.dig_P8)/32768.0;
    *pressure = p+(var1+var2+((double)bmp_dat.dig_P7))/16.0;

    return 0;
}


int main(int argc, char const *argv[])
{
    int fd = 0;
    struct bmp280_dat bmp_dat;
    int res = 0;
    float pressure = 0;
    float Temp = 0;


    fd = open( "/dev/bmp280",O_RDWR );
    if( fd < 0 )
    {
        printf( "file open failed\r\n" );
        return 0;
    }

    while(1)
    {
        res = ioctl( fd, BMP280_GET, &bmp_dat);
        calculate_pressure( bmp_dat, &pressure, &Temp );
        printf( "pressure = %3.3f kpa, Tempture = %2.3f C\r\n", pressure/1000, Temp );
        sleep( 1 );
    }


    close( fd );

    return 0;
}
